const http = require("http");
const fs = require("fs");
const qs = require("querystring");
const { groupCollapsed } = require("console");

http.createServer((req,res)=>{
    if(req.url !== "/favicon.ico"){
        if(req.url.includes("/api")){
            dataRequire(req, res)
        }else{
            fileRequire(req, res)
        }
    }
}).listen(3000);

function dataRequire(req, res){
    let str = "";
    req.on("data",(c)=>{
        str += c
    })
    req.on("end",()=>{
        let dataObj = null;
        if(str){
            dataObj = qs.parse(str);
        }else{
            dataObj = qs.parse(req.url.split("?")[1]);
        }
        switch(dataObj.type){
            case "register":
                register(req,res,dataObj);break;
            case "login":
                login(req,res,dataObj);break;
            case "goods":
                goods(req,res,dataObj);break;
        }
    })
}

function goods(req,res,dataObj){
    fs.readFile("./data/goods.json","utf-8",(err,data)=>{
        let msg;
        if(err){
            msg = {code:400,title:"请求失败",data:"NOT DATA"}
        }else{
            msg = {code:200,title:"请求成功",data:JSON.parse(data)}
        }
        res.write(JSON.stringify(msg));
        res.end();

    })
   
}



const userMsg = [];
function register(req,res,dataObj){
    console.log(dataObj);
    console.log("正在注册");
    const obj = {};
    const flag = userMsg.some((val)=>val.username===dataObj.username);
    if(flag){
        obj.code = 0;
        obj.title = "用户名重复";
        obj.data = "NOT DATA";
    }else{
        userMsg.push({
            username:dataObj.username,
            password:dataObj.password
        })
        obj.code = 1;
        obj.title = "注册成功";
        obj.data = "NOT DATA";
    }
    res.write(JSON.stringify(obj));
    res.end();

}
function login(req,res,dataObj){
    console.log(dataObj);
    console.log("正在登录");
    let i = 0;
    const flag = userMsg.some((val,idx)=>{
        i = idx;
        return val.username===dataObj.username;
    });
    // console.log(flag)
    // console.log(userMsg[i].password)
    const obj = {};
    // 用户名不存在
    if(flag){
        if(dataObj.password===userMsg[i].password){
            // console.log(1)
            obj.code = 1;
            obj.title = "登录成功";
            obj.data = dataObj.username;
        }else{
            obj.code = 0;
            obj.title = "用户名密码不符";
            obj.data = "NOT DATA";
        }
    }else{
        obj.code = 2;
        obj.title = "用户名不存在";
        obj.data = "NOT DATA";
    }

    res.write(JSON.stringify(obj));
    res.end();

}


function fileRequire(req, res){
    const myURL = new URL("http://localhost:3000" + req.url)
    fs.readFile("./www" + myURL.pathname,(err, data)=>{
        if(err){
            res.write("404");
        }else{
            res.write(data);
        }
        res.end();
    })
}

